package com.ys.web.yinsheng.controller;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.ys.base.BaseParam;
import com.ys.utils.aliyun.AliyunSmsUtils;
import com.ys.utils.base.j2se.*;
import com.ys.utils.pay.Result;
import com.ys.utils.spring.properties.Config;
import com.ys.web.goods.order.model.Order;
import com.ys.web.goods.order.service.OrderService;
import com.ys.web.mobao.service.MobaoWithholdingService;
import com.ys.web.pay.PayEnum;
import com.ys.web.pay.PayService;
import com.ys.web.pay.manager.PayManager;
import com.ys.web.pay.model.PayOrder;
import com.ys.web.pay.model.WithdrawRecord;
import com.ys.web.user.info.UserInfo;
import com.ys.web.user.info.UserInfoService;
import com.ys.web.yinsheng.model.*;
import com.ys.web.yinsheng.service.YinShengService;
import com.ys.web.yinsheng.util.ServiceEnum;
import com.ys.web.yinsheng.util.YinShengClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: dhf
 * @ClassName: YinShengCallBackController
 * @Date: 2022/7/21 21:41
 * @Description:银盛回调
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/ys/callBack")
public class YinShengCallBackController {
    @Autowired
    private YinShengService yinShengService;
    @Autowired
    private PayService payService;
    @Autowired
    private MobaoWithholdingService mobaoWithholdingService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserInfoService userInfoService;
    /**
     * @作者: dhf
     * @名称:进件回调通知
     * @param callBackNofify
     * @时间: 2022/7/20 20:58
     * @备注:
     * @返回值: java.lang.String
     */
    @RequestMapping("/jj/notify")
    public String jjNotify(CallBackNofify callBackNofify){
        log.info("jjNotify--------"+callBackNofify);
        BizResponseJson bizResponseJson = new BizResponseJson(callBackNofify.bizResponseJson);
        MerchantInfo merchantInfo = null;
        ReportInfo reportInfo = null;
        //01-进件通知  02-报备通知
        if(bizResponseJson.notifyType.equals("01")){
            merchantInfo = new MerchantInfo(bizResponseJson.merchantInfo);
        }
        if(bizResponseJson.notifyType.equals("02")){
            reportInfo = new ReportInfo(bizResponseJson.reportInfo);
        }
        //保存银盛进件信息
        YinShengMerchantInfo yinShengMerchantInfo = new YinShengMerchantInfo(bizResponseJson,merchantInfo,reportInfo);
        //添加银盛商户信息
        yinShengService.insert(yinShengMerchantInfo);
        return "success";
    }

    /**
     * @作者: dhf
     * @名称:充值回调
     * @param callBackNofify
     * @时间: 2022/7/21 21:59
     * @备注:
     * @返回值: java.lang.String
     */
    @RequestMapping("/recharge/notify")
    public String rechargeNotify(CallBackNofify callBackNofify){
        log.info("rechargeNotify--------"+callBackNofify);
        RechargeInfo rechargeInfo =  JsonUtil.jsonToBean(callBackNofify.bizResponseJson, RechargeInfo.class);
        if(StringHandler.isEmpty(rechargeInfo)){
            log.error("充值回调错误");
            return "success";
        }
        if ("SUCCESS".equals(rechargeInfo.state)) { // 充值成功
            PayOrder payOrder = payService.payOrderByNo(rechargeInfo.requestNo);
            if(payOrder.payStatus.equals("1")){
                return "success";
            }
            // 更新订单状态
            PayOrder _payOrder = new PayOrder();
            _payOrder.setId(payOrder.getId());
            _payOrder.setPayStatus(PayEnum.PayStatus.PAID.getCode());
            _payOrder.setPayTime(new Date());
            _payOrder.setDayKey(DateUtil.getYYMMDD());
            int i = payService.payOrderStatusChange(_payOrder);
            if(i<=0){
                return "success";
            }
            //充值成功计算支付公司坐扣金额并返还用户
//            long amount = payOrder.getAmount();
//            int fee;
//            //100元的倍数不需要额外追加1分钱
//            BigDecimal dee = new BigDecimal(Convert.objToStr(amount));
//            fee = dee.multiply(new BigDecimal(Config.pp.getOrDefault("wallet.recharge.transfer.rate","0.0026"))).intValue();
//            if(amount%10000!=0){
//                fee += 1;
//            }
            // TODO 银盛内部转账补手续费逻辑：YsTransferByRechargeMq
//            RedisMessage.getInstence(ProjectConstants.MQ_WALLET_TRANSFER_RECHARGE)
//                    .appendData("userId", busiUser.getId())
//                    .appendData("redUserId", Config.pp.get("wallet.withholding.tg.user.id"))
//                    .appendData("amount", fee)
//                    .sendQueue();
            // 修改用户账户金额
            Result<?> result1 = PayManager.accountModify(StringHandler.getLong(payOrder.getBusyId()), PayEnum.AccountFlowType.TYPE_RECHARGE,
                    payOrder.getAmount(),
                    String.format("余额充值-来自%s(%s)",payOrder.getBankName(),payOrder.getCardNo().substring(payOrder.getCardNo().length()-4)),2);

            try {
                UserInfo userInfo = userInfoService.getUserInfoById(StringHandler.getLong(payOrder.getBusyId()));
                if(StringHandler.isNotEmpty(userInfo)) {
                    //发送短信
                    Map<String, Object> msgMap = new HashMap<>();
                    msgMap.put("money", StringHandler.fenToYuan(payOrder.amount + ""));
                    msgMap.put("name", StringHandler.isEmpty(userInfo.getPhone())?userInfo.getNickName():userInfo.getPhone());
                    if(StringHandler.isNotEmpty( userInfo.getPhone())){
                        SendSmsResponse sendSmsResponse = AliyunSmsUtils.sendMsg(Config.pp.get("ys.sms.recharge.id"), userInfo.getPhone(), JSON.toJSONString(msgMap));
                        if (!sendSmsResponse.getCode().equals("OK")) {
                            log.error("充值短信提示发送失败：" + JSON.toJSON(sendSmsResponse));
                        }
                    }
                }
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            } catch (Exception e) {
                log.error("充值短信提示发送错误",e);
            }
            // 充值成功，发送红包推送
            if(!result1.success()){
                Logger.error("充值修改账户金额失败："+ JSON.toJSONString(rechargeInfo));
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "FAIL";
            }
//            Result<Map<String, String>> send = Result.newFailure();
//            WalletBase create = null;
//            if(type== EnumType.MessageCode.MESSAGE_RED_PACK.getCode()){
//                create = JSON.parseObject(JSON.toJSONString(data.get("create")),RedPacketCreate.class);
//                RedPacketCreate redPacketCreate = (RedPacketCreate) create;
//                // 我来发红包了
//                send = upayService.giveRedPackage(Convert.objToStr(redPacketCreate.getPacketType()),create.getAmount(),
//                        Convert.objToStr(redPacketCreate.getPacketCount()),UpayEnum.payMentType.BANK.getCode(),
//                        create.getGp().equals("1")?create.getReceivedId():create.getReceivedIds(),
//                        Convert.objToStr(busiUser.getId()),create.getRemark(),create.getReceivedId());
//                if(redPacketCreate.getPacketType()==4){
//                    create.setReceivedIds(McodeHandler.to32Radix(Convert.objToLong(create.getReceivedIds())));
//                }
//            }else if (type== EnumType.MessageCode.MESSAGE_TRANSFER.getCode()){
//                // 我来发转账了
//                create = JSON.parseObject(JSON.toJSONString(data.get("create")), TransferCreate.class);
//                send = upayService.giveTransfer(create.getAmount(),
//                        create.getGp().equals("1")?create.getReceivedId():create.getReceivedIds(),
//                        Convert.objToStr(busiUser.getId()),
//                        create.getRemark(),create.getGp(),
//                        create.getGp().equals("2")?create.getReceivedId():null,
//                        UpayEnum.payMentType.BANK.getCode());
//                if(create.getGp().equals("2")){
//                    create.setReceivedIds(McodeHandler.to32Radix(Convert.objToLong(create.getReceivedIds())));
//                }
//            }
            // 发送推送
//            if(send.success()){
//                if(!UPayManager.send(Convert.objToLong(userId),create,send.getResult().get("redId"))){
////                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    Logger.error("银行卡发送红包失败"+JSON.toJSONString(create));
//                    return false;
//                }
//            }
        }else{ // 充值失败
            PayOrder payOrder = payService.payOrderByNo(rechargeInfo.requestNo);
            // 更新订单状态
            PayOrder _payOrder = new PayOrder();
            _payOrder.setId(payOrder.getId());
            _payOrder.setPayStatus(PayEnum.PayStatus.FAIL.getCode());
            payService.payOrderStatusChange(_payOrder);
        }
        return "success";
    }

    /**
     * @作者: dhf
     * @名称:钱包消费回调
     * @param callBackNofify
     * @时间: 2022/7/21 21:59
     * @备注:
     * @返回值: java.lang.String
     */
    @RequestMapping("/consume/notify")
    public String consumeNotify(CallBackNofify callBackNofify){
        log.info("consumeNotify--------"+callBackNofify);
        Map<String,Object> bizResponseJson = JsonUtil.jsonToBean(callBackNofify.bizResponseJson,Map.class);
        String state = StringHandler.getString(bizResponseJson.get("state"));
        if(StringHandler.isEmpty(state)){
            log.info("consumeNotify--------支付状态错误");
            return "success";
        }
        String requestNo = StringHandler.getString(bizResponseJson.get("requestNo"));
        if(state.equals("SUCCESS")){
            Order order = orderService.goodsOrderSnInfo(requestNo,-1);
            if(order.getStatus()!=-1){
                return "success";
            }
            // 修改支付状态
            String linkId = StringHandler.getString(bizResponseJson.get("linkId"));
            String tradeSn = StringHandler.getString(bizResponseJson.get("tradeSn"));
            orderService.orderPayStatus(StringHandler.getString(requestNo),1,DateHandler.getLongFormatDate(),linkId,tradeSn);
//            if(order.type==2)
//                // 修改用户账户金额
//                Result<?> result1 = PayManager.accountModify(StringHandler.getLong(order.getUid()), PayEnum.AccountFlowType.TYPE_RECHARGE,
//                        payOrder.getAmount(),
//                        payOrder.getPayType().equals(PayEnum.payMentType.BANK.getCode())?String.format("余额充值-来自%s(%s)",payOrder.getBankName(),payOrder.getCardNo().substring(payOrder.getCardNo().length()-4)):"零钱充值-来自支付宝");
//                // 支付失败
//                if(!result1.success()){
//                    Logger.error("充值修改账户金额失败："+JSON.toJSONString(payOrder));
//                }
        }else{
            orderService.orderPayStatus(StringHandler.getString(requestNo),10,DateUtil.getDatetimeLong(),"","");

        }
        return "success";
    }

    /**
     * @作者: dhf
     * @名称:提现回调
     * @param callBackNofify
     * @时间: 2022/7/21 21:59
     * @备注:
     * @返回值: java.lang.String
     */
    @RequestMapping("/withdraw/notify")
    public String withdrawNotify(CallBackNofify callBackNofify){
        log.info("withdrawNotify--------"+callBackNofify);
        Map<String,Object> bizResponseJson = JsonUtil.jsonToBean(callBackNofify.bizResponseJson,Map.class);
        String state = StringHandler.getString(bizResponseJson.get("state"));
        if(StringHandler.isEmpty(state)){
            log.info("withdrawNotify--------提现状态错误");
            return "success";
        }
        String requestNo = StringHandler.getString(bizResponseJson.get("requestNo"));
        WithdrawRecord withdrawRecord = mobaoWithholdingService.getWithdrawRecordByOrderId(requestNo);
        if(StringHandler.isEmpty(withdrawRecord)){
            log.info("withdrawNotify----["+requestNo+"]----提现信息不存在");
            return "success";
        }
        if(StringHandler.getInt(withdrawRecord.withdrawStatus)==2){
            log.info("withdrawNotify----["+requestNo+"]----提现已经成功");
            return "success";
        }
        if(state.equals("SUCCESS")){
            int i = mobaoWithholdingService.updateWithdrawRecordStatus(withdrawRecord);
            if(i <= 0) {
                Logger.info("提现回调给到处理中订单--该订单已处理",JsonUtil.toJson(callBackNofify));
                return "success";
            }
            UserMerchant userMerchant = yinShengService.userMerchant(withdrawRecord.userId+"");
            //提现成功扣除冻结金额
            PayManager.accountModify(withdrawRecord.getUserId(), PayEnum.AccountFlowType.WITHDRAWAL_SUCCESS, withdrawRecord.getAmount(), withdrawRecord.getUserId()+":提现成功扣除冻结金额",2);
            withdrawRecord.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_SUCCESS.getCode());
            //手续费转账，转到尚品好物账户
            //收取手续费账户
            Map<String,Object> collectionUser = yinShengService.collectionUser();
            long collectionUid = 47144;
            String payeeMerchantNo = "Y151119861025195";
            if(StringHandler.isNotEmpty(collectionUser)) {
                payeeMerchantNo = StringHandler.getString(collectionUser.get("merchantNo"));
                collectionUid = StringHandler.getLong(collectionUser.get("uid"));
            }
            if(withdrawRecord.getFee()>100) {
                // 组装业务参
                Map<String, Object> requestMap1 = new HashMap<>();
                String requestNo1 = BaseParam.getOrderSN();
                requestMap1.put("requestNo", requestNo1);
                requestMap1.put("payeeMerchantNo", payeeMerchantNo);//收款方银盛商户号
                requestMap1.put("payerMerchantNo", userMerchant.merchantNo);//付款方银盛商户号
                requestMap1.put("transferType","C2C");//转账类型 P2B-平台转商户 P2C-平台转用户 B2P-商户转平台 B2B-商户转商户 B2C-商户转用户 C2C-用户转用户 A2A-资金归集
                requestMap1.put("orderDesc", "提现手续费");//商品名称/订单标题
                requestMap1.put("amount", StringHandler.fenToYuan(withdrawRecord.fee + ""));//提现金额，单位：元
                requestMap1.put("remark", "手续费转账");
                RequestData requestData = new RequestData(requestMap1);
                YinShengClient yinShengClient = new YinShengClient(ServiceEnum.TRANSFER_INNER);
                String callback1 = yinShengClient.requestStrApi(requestData);
                Map<String, Object> obj = JsonUtil.jsonToBean(callback1, Map.class);
                int status = 2;
                String remark = "";
                if (!obj.get("code").equals("SYS000")) {
                    remark = "银盛提现回调:" + StringHandler.getString(obj.get("msg"));
                    log.error(remark);
                    status = 1;
                } else {
                    if (StringHandler.isNotEmpty(obj.get("bizResponseJson"))) {
                        Map<String, Object> bizResponseJson1 = JsonUtil.jsonNullToBean(JsonUtil.toJson(obj.get("bizResponseJson")), Map.class);
                        if (!bizResponseJson1.get("subCode").equals("COM000")) {
                            remark = "银盛提现回调:" + StringHandler.getString(bizResponseJson1.get("subMsg"));
                            log.error(remark);
                            status = 1;
                        }
                    } else {
                        remark = "银盛提现回调:返回信息bizResponseJson为空";
                        log.error(remark);
                        status = 1;
                    }
                }
            //记录手续费
            mobaoWithholdingService.updateSxf(requestNo,status,remark);
            }
            //手续费账户，收取提现手续费
            PayManager.accountModify(collectionUid, PayEnum.AccountFlowType.PAY_ORDER_MONEY_FREE, withdrawRecord.getFee(), withdrawRecord.userId+":提现手续费",2);
            //添加手续费账户累计资金
            yinShengService.collectionUserMoney(collectionUid,withdrawRecord.getFee());
            try {
                UserInfo userInfo = userInfoService.getUserInfoById(StringHandler.getLong(withdrawRecord.getUserId()));
                if(StringHandler.isNotEmpty(userInfo)) {
                    //发送短信
                    Map<String, Object> msgMap = new HashMap<>();
                    msgMap.put("money", StringHandler.fenToYuan(withdrawRecord.getWithdrawAmount() + ""));
                    msgMap.put("name", StringHandler.isEmpty(userInfo.getPhone())?userInfo.getNickName():userInfo.getPhone());
                    if(StringHandler.isNotEmpty( userInfo.getPhone())){
                        SendSmsResponse sendSmsResponse = AliyunSmsUtils.sendMsg(Config.pp.get("ys.sms.withdraw.id"), userInfo.getPhone(), JSON.toJSONString(msgMap));
                        if (!sendSmsResponse.getCode().equals("OK")) {
                            log.error("提现短信提示发送失败：" + JSON.toJSON(sendSmsResponse));
                        }
                    }
                }
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            } catch (Exception e) {
                log.error("提现短信提示发送错误",e);
            }
        }
        if(state.equals("FAILED")){
            int i = mobaoWithholdingService.updateWithdrawRecordStatus(withdrawRecord);
            if(i <= 0) {
                Logger.info("提现回调给到处理中订单--该订单已处理",JsonUtil.toJson(callBackNofify));
                return "success";
            }
            //提现失败退回余额
            PayManager.accountModify(withdrawRecord.getUserId(), PayEnum.AccountFlowType.WITHDRAWAL_FAIL, withdrawRecord.getAmount(), Convert.objToStr(withdrawRecord.getUserId()),2);
            withdrawRecord.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_FAIL.getCode());
        }
        withdrawRecord.setDayKey(DateUtil.getYYMMDD());
        mobaoWithholdingService.updateWithdrawRecordStatusTask(withdrawRecord);
        return "success";
    }
    /**
     * @作者: dhf
     * @名称:提现任务回调
     * @param callBackNofify
     * @时间: 2022/7/21 21:59
     * @备注:
     * @返回值: java.lang.String
     */
    @RequestMapping("/withdraw/task/notify")
    public String withdrawTaskNotify(CallBackNofify callBackNofify){
        log.info("withdrawNotify--------"+callBackNofify);
        Map<String,Object> bizResponseJson = JsonUtil.jsonToBean(callBackNofify.bizResponseJson,Map.class);
        String state = StringHandler.getString(bizResponseJson.get("state"));
        if(StringHandler.isEmpty(state)){
            log.info("withdrawNotify--------提现状态错误");
            return "success";
        }
        String requestNo = StringHandler.getString(bizResponseJson.get("requestNo"));
        WithdrawRecord withdrawRecord = mobaoWithholdingService.getWithdrawRecordByOrderId(requestNo);
        if(StringHandler.isEmpty(withdrawRecord)){
            log.info("withdrawNotify----["+requestNo+"]----提现信息不存在");
            return "success";
        }
        if(StringHandler.getInt(withdrawRecord.withdrawStatus)==2){
            log.info("withdrawNotify----["+requestNo+"]----提现已经成功");
            return "success";
        }
        if(state.equals("SUCCESS")){
            int i = mobaoWithholdingService.updateWithdrawRecordStatus(withdrawRecord);
            if(i <= 0) {
                Logger.info("提现回调给到处理中订单--该订单已处理",JsonUtil.toJson(callBackNofify));
                return "success";
            }
            UserMerchant userMerchant = yinShengService.userMerchant(withdrawRecord.userId+"");
            //提现成功扣除冻结金额
            PayManager.accountModify(withdrawRecord.getUserId(), PayEnum.AccountFlowType.WITHDRAWAL_SUCCESS, withdrawRecord.getAmount(), withdrawRecord.getUserId()+":提现成功扣除冻结金额",2);
            withdrawRecord.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_SUCCESS.getCode());
            //手续费转账，转到尚品好物账户
            //收取手续费账户
            Map<String,Object> collectionUser = yinShengService.collectionUser();
            long collectionUid = 47144;
            String payeeMerchantNo = "Y151119861025195";
            if(StringHandler.isNotEmpty(collectionUser)) {
                payeeMerchantNo = StringHandler.getString(collectionUser.get("merchantNo"));
                collectionUid = StringHandler.getLong(collectionUser.get("uid"));
            }
            if(withdrawRecord.getFee()>100) {
                // 组装业务参
                Map<String, Object> requestMap1 = new HashMap<>();
                String requestNo1 = BaseParam.getOrderSN();
                requestMap1.put("requestNo", requestNo1);
                requestMap1.put("payeeMerchantNo", payeeMerchantNo);//收款方银盛商户号
                requestMap1.put("payerMerchantNo", userMerchant.merchantNo);//付款方银盛商户号
                requestMap1.put("transferType","C2C");//转账类型 P2B-平台转商户 P2C-平台转用户 B2P-商户转平台 B2B-商户转商户 B2C-商户转用户 C2C-用户转用户 A2A-资金归集
                requestMap1.put("orderDesc", "提现手续费");//商品名称/订单标题
                requestMap1.put("amount", StringHandler.fenToYuan(withdrawRecord.fee + ""));//提现金额，单位：元
                requestMap1.put("remark", "手续费转账");
                RequestData requestData = new RequestData(requestMap1);
                YinShengClient yinShengClient = new YinShengClient(ServiceEnum.TRANSFER_INNER);
                String callback1 = yinShengClient.requestStrApi(requestData);
                Map<String, Object> obj = JsonUtil.jsonToBean(callback1, Map.class);
                int status = 2;
                String remark = "";
                if (!obj.get("code").equals("SYS000")) {
                    remark = "银盛提现回调:" + StringHandler.getString(obj.get("msg"));
                    log.error(remark);
                    status = 1;
                } else {
                    if (StringHandler.isNotEmpty(obj.get("bizResponseJson"))) {
                        Map<String, Object> bizResponseJson1 = JsonUtil.jsonNullToBean(JsonUtil.toJson(obj.get("bizResponseJson")), Map.class);
                        if (!bizResponseJson1.get("subCode").equals("COM000")) {
                            remark = "银盛提现回调:" + StringHandler.getString(bizResponseJson1.get("subMsg"));
                            log.error(remark);
                            status = 1;
                        }
                    } else {
                        remark = "银盛提现回调:返回信息bizResponseJson为空";
                        log.error(remark);
                        status = 1;
                    }
                }
                //记录手续费
                mobaoWithholdingService.updateSxf(requestNo,status,remark);
            }
            //手续费账户，收取提现手续费
            PayManager.accountModify(collectionUid, PayEnum.AccountFlowType.PAY_ORDER_MONEY_FREE, withdrawRecord.getFee(), withdrawRecord.userId+":提现手续费",2);
            //添加手续费账户累计资金
            yinShengService.collectionUserMoney(collectionUid,withdrawRecord.getFee());
            try {
                UserInfo userInfo = userInfoService.getUserInfoById(StringHandler.getLong(withdrawRecord.getUserId()));
                if(StringHandler.isNotEmpty(userInfo)) {
                    //发送短信
                    Map<String, Object> msgMap = new HashMap<>();
                    msgMap.put("money", StringHandler.fenToYuan(withdrawRecord.getWithdrawAmount() + ""));
                    msgMap.put("name", StringHandler.isEmpty(userInfo.getPhone())?userInfo.getNickName():userInfo.getPhone());
                    if(StringHandler.isNotEmpty( userInfo.getPhone())){
                        SendSmsResponse sendSmsResponse = AliyunSmsUtils.sendMsg(Config.pp.get("ys.sms.withdraw.id"), userInfo.getPhone(), JSON.toJSONString(msgMap));
                        if (!sendSmsResponse.getCode().equals("OK")) {
                            log.error("提现短信提示发送失败：" + JSON.toJSON(sendSmsResponse));
                        }
                    }
                }
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            } catch (Exception e) {
                log.error("提现短信提示发送错误",e);
            }
        }
        if(state.equals("FAILED")){
            int i = mobaoWithholdingService.updateWithdrawRecordStatus(withdrawRecord);
            if(i <= 0) {
                Logger.info("提现回调给到处理中订单--该订单已处理",JsonUtil.toJson(callBackNofify));
                return "success";
            }
            //提现失败退回余额
            PayManager.accountModify(withdrawRecord.getUserId(), PayEnum.AccountFlowType.WITHDRAWAL_FAIL, withdrawRecord.getAmount(), Convert.objToStr(withdrawRecord.getUserId()),2);
            withdrawRecord.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_FAIL.getCode());
        }
        withdrawRecord.setDayKey(DateUtil.getYYMMDD());
        mobaoWithholdingService.updateWithdrawRecordStatusTask(withdrawRecord);
        return "success";
    }
    /**
     * @作者: dhf
     * @名称:退款回调
     * @param callBackNofify
     * @时间: 2022/7/21 21:59
     * @备注:
     * @返回值: java.lang.String
     */
    @RequestMapping("/refund/notify")
    public String refundNotify(CallBackNofify callBackNofify){
        log.info("refundNotify--------"+callBackNofify);
        Map<String,Object> bizResponseJson = JsonUtil.jsonToBean(callBackNofify.bizResponseJson,Map.class);
        if(StringHandler.isEmpty(bizResponseJson)){
            log.error("refundNotify----返回信息为空");
            return "success";
        }
        String state = StringHandler.getString(bizResponseJson.get("state"));
        String origRequestNo = StringHandler.getString(bizResponseJson.get("origRequestNo"));
        Order payOrder = orderService.goodsOrderSnInfo(origRequestNo,12);
        if(StringHandler.isEmpty(payOrder)){
            log.error("refundNotify----orderSn["+origRequestNo+"]----支付订单查询为空");
            return "success";
        }
        if(state.equals("SUCCESS")){
            if(payOrder.getStatus()==12){
                String refundSn = StringHandler.getString(bizResponseJson.get("refundSn"));
                long amount = StringHandler.getLong(StringHandler.getString(bizResponseJson.get("amount")));
                int i = orderService.goodsOrderRefund(payOrder.getId(),refundSn,DateHandler.getLongFormatDate());
                if(i<=0){
                    log.error("refundNotify--------SUCCESS退单失败，订单ID["+payOrder.getId()+"],请联系技术处理");
                }else{
                    //订单收款人账号退款
                    //PayManager.accountModify(payOrder.collectionUid, PayEnum.AccountFlowType.PAY_ORDER_MONEY_REFUND, amount, "订单支付退款");
                }
            }
        }else{
            String refundSn = StringHandler.getString(bizResponseJson.get("refundSn"));
            int i = orderService.goodsOrderFailed(payOrder.getId(),refundSn,DateHandler.getLongFormatDate());
            log.error("refundNotify--------Failed退单失败，订单ID["+payOrder.getId()+"],请联系技术处理");
        }
        return "success";
    }
}
